import { createRouter, createWebHistory } from 'vue-router'
import Layout from '../views/Layout/index.vue'
import Home from '../views/Home/index.vue'
import ShopCart from '../views/Home/components/ShopCart.vue'
import Login from '@/views/LoginView.vue'
import UserInfo from '@/views/UserInfo/index.vue'


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'layout',
      component: Layout,
      meta: {
        isAuth: true,
      },
      children: [
        {
          path: '/',
          component: Home,
          meta: {
            isAuth: true,
            title: '首页'
          }
        },
        {
          path: '/cart',
          name: 'shopCart',
          component: ShopCart,
          meta: {
            isAuth: true,
            title: '购物车'
          }
        },
        {
          path: '/userInfo',
          name: 'userInfo',
          component: UserInfo,
          meta: {
            isAuth: true,
            title: '购物车'
          }
        }
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: Login,
      meta: {
        title: '登录'
      }
    }

  ]
})

router.beforeEach((to, from, next) => {
  //如果路由需要跳转
  if (to.meta.isAuth) {
    //判断 如果school本地存储是qinghuadaxue的时候，可以进去
    if (localStorage.getItem('token') != null) {
      next()  //放行
    } else {
      next({
        path: '/login',
        query: {
          redirect: to.fullPath // 把要跳转的页面路径作为参数传到登录页面
        }
      })
    }
  } else {
    // 否则，放行
    next()
  }
})




export default router
